package com.xiaoshuidi.cloud.module.rooms.framework.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xiaoshuidi.cloud.module.rooms.framework.config.ConfigValues;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Component
public class GaoDeUtil {

    @Resource
    private ConfigValues configValues;

    public String addressToLatitudeAndLongitudeUrl(String address,String city){
        String location = " , ";
        try {
            String url = configValues.getAddressToLatitudeAndLongitudeUrl().replace("*{city}",city);
            String requestUrl = StrUtil.format(url, address, configValues.getGaodeKey());
            String resp = HttpUtil.get(requestUrl);
            JSONObject jsonObject = JSONObject.parseObject(resp);
            if ("1".equals(jsonObject.get("status"))){
                List<JSONObject> geocodes = (List<JSONObject>) jsonObject.get("geocodes");
                location = (String) geocodes.get(0).get("location");
                log.info("地址: {}，经纬度: {}", address, location);
            }else {
                location = "";
            }
        } catch (Exception e) {
            log.error("地址转经纬度异常:", e);
        }
        return location;
    }

    /**
     * 根据经纬度计算距离
     * @param origins 起始地 经度,纬度
     * @param destination 目的地 经度,纬度
     * @return
     */
    public Double calculateDistance(String origins, String destination){
        Double meter = null;
        try {
            String getDistanceUrl = StrUtil.format(configValues.getGetDistanceUrl(), origins, destination, configValues.getGaodeKey());
            String distanceResp = HttpUtil.get(getDistanceUrl);
            JSONObject jsonObject = JSONObject.parseObject(distanceResp);
            String status = (String) jsonObject.get("status");
            if ("1".equals(status)) {
                JSONArray results = (JSONArray) jsonObject.get("results");
                JSONObject jsonObject1 = (JSONObject) results.get(0);
                meter = Double.valueOf(jsonObject1.get("distance").toString());
            }
        } catch (NumberFormatException e) {
            log.error("根据经纬度计算距离异常", e);
        }
        return meter;
    }
}
